import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { Table, Button, Modal, Form, Input, message, Popconfirm, Switch, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import MainLayout from '../../components/Layout/MainLayout';
import { getContactList, addContact, updateContact, deleteContact } from '../../api/userApi';
import { Contact } from '../../api/types';

const ContactsContainer = styled.div`
  max-width: 1000px;
  margin: 0 auto;
`;

const PageHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
`;

const PageTitle = styled.h2`
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #333;
`;

const TableActions = styled.div`
  display: flex;
  gap: 8px;
  
  .edit-button {
    color: #1890ff;
  }
  
  .delete-button {
    color: #ff4d4f;
  }
`;

const DescriptionText = styled.p`
  margin-bottom: 20px;
  color: #666;
`;

const ContactsPage: React.FC = () => {
  const [form] = Form.useForm();
  const [contacts, setContacts] = useState<Contact[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingContact, setEditingContact] = useState<Contact | null>(null);
  
  // 获取联系人列表
  const fetchContacts = async () => {
    try {
      setLoading(true);
      const response = await getContactList();
      
      if (response.code === 0) {
        setContacts(response.data);
      } else {
        message.error(response.message || '获取联系人列表失败');
      }
    } catch (error) {
      console.error('获取联系人列表失败', error);
      message.error('获取联系人列表失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  useEffect(() => {
    fetchContacts();
  }, []);
  
  // 添加或更新联系人
  const handleSaveContact = async (values: any) => {
    try {
      setLoading(true);
      
      if (editingContact) {
        // 更新联系人
        const response = await updateContact(editingContact.id, values);
        
        if (response.code === 0) {
          message.success('更新联系人成功');
          setModalVisible(false);
          fetchContacts();
        } else {
          message.error(response.message || '更新联系人失败');
        }
      } else {
        // 添加联系人
        const response = await addContact(values);
        
        if (response.code === 0) {
          message.success('添加联系人成功');
          setModalVisible(false);
          fetchContacts();
        } else {
          message.error(response.message || '添加联系人失败');
        }
      }
    } catch (error) {
      console.error('保存联系人失败', error);
      message.error('保存联系人失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  // 删除联系人
  const handleDeleteContact = async (contactId: string) => {
    try {
      setLoading(true);
      
      const response = await deleteContact(contactId);
      
      if (response.code === 0) {
        message.success('删除联系人成功');
        fetchContacts();
      } else {
        message.error(response.message || '删除联系人失败');
      }
    } catch (error) {
      console.error('删除联系人失败', error);
      message.error('删除联系人失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  // 打开添加或编辑联系人模态框
  const showContactModal = (contact?: Contact) => {
    setEditingContact(contact || null);
    
    if (contact) {
      form.setFieldsValue({
        name: contact.name,
        phone: contact.phone,
        email: contact.email || '',
        isDefault: contact.isDefault || false
      });
    } else {
      form.resetFields();
    }
    
    setModalVisible(true);
  };
  
  // 表格列配置
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: Contact) => (
        <>
          {text}
          {record.isDefault && <Tag color="blue" style={{ marginLeft: 8 }}>默认</Tag>}
        </>
      )
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      render: (text: string) => text || '未设置'
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: Contact) => (
        <TableActions>
          <Button
            type="text"
            icon={<EditOutlined />}
            className="edit-button"
            onClick={() => showContactModal(record)}
          />
          
          <Popconfirm
            title="确定删除此联系人吗？"
            onConfirm={() => handleDeleteContact(record.id)}
            okText="是"
            cancelText="否"
            icon={<ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />}
          >
            <Button
              type="text"
              icon={<DeleteOutlined />}
              className="delete-button"
            />
          </Popconfirm>
        </TableActions>
      )
    }
  ];
  
  return (
    <MainLayout>
      <ContactsContainer>
        <PageHeader>
          <PageTitle>常用联系人管理</PageTitle>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => showContactModal()}
          >
            添加联系人
          </Button>
        </PageHeader>
        
        <DescriptionText>
          添加常用联系人信息，预订时可以直接选择，无需重复填写
        </DescriptionText>
        
        <Table
          columns={columns}
          dataSource={contacts}
          rowKey="id"
          pagination={false}
          loading={loading}
          locale={{ emptyText: '暂无常用联系人' }}
        />
        
        <Modal
          title={editingContact ? '编辑联系人' : '添加联系人'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          footer={null}
          destroyOnClose
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSaveContact}
          >
            <Form.Item
              name="name"
              label="姓名"
              rules={[
                { required: true, message: '请输入姓名' },
                { max: 20, message: '姓名不能超过20个字符' }
              ]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>
            
            <Form.Item
              name="phone"
              label="手机号"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>
            
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { type: 'email', message: '请输入正确的邮箱地址' }
              ]}
            >
              <Input placeholder="请输入邮箱（选填）" />
            </Form.Item>
            
            <Form.Item
              name="isDefault"
              valuePropName="checked"
            >
              <Switch />
              <span style={{ marginLeft: 8 }}>设为默认联系人</span>
            </Form.Item>
            
            <div style={{ textAlign: 'right' }}>
              <Button style={{ marginRight: 8 }} onClick={() => setModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                确定
              </Button>
            </div>
          </Form>
        </Modal>
      </ContactsContainer>
    </MainLayout>
  );
};

export default ContactsPage; 